package com.amazon.shop.service.impl;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazon.shop.bean.entity.Emailmodel;
import com.amazon.shop.bean.entity.Evalform;
import com.amazon.shop.bean.entity.Store;
import com.amazon.shop.service.IEvalformService;
import com.amazon.shop.service.IStoreService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 创建时间：15:48 2021/3/25
 *
 * @author lzj
 * @since JDK 1.8.0_171
 * 类说明：
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ---------------------------------------------------------*
 */
@Component
public class AsyncSendEmail {

    @Autowired
    private IEvalformService evalformService;

    @Autowired
    private IStoreService toreService;

    @Async
    public void sendEmail(List<Integer> evalformIds, Emailmodel emailmodel){
        for (Integer evalformId : evalformIds) {
            Evalform evalform = evalformService.getById(evalformId);
            Integer storeid = evalform.getStoreid();
            Store byId = toreService.getById(storeid);
            MailAccount account = new MailAccount();
            account.setHost(byId.getEmailhost());
            account.setPort(byId.getEmailprot());
            account.setAuth(true);
            account.setFrom(byId.getEmail());
            account.setUser(byId.getEmail());
            account.setPass(byId.getEmailpwd());
            account.setSslEnable(true);
            try {
                MailUtil.send(account, evalform.getEvalemail(), emailmodel.getMname(), emailmodel.getContent(), true);
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id",evalformId);
                updateWrapper.set("issend",1);
                evalformService.update(updateWrapper);
            }catch (Exception e) {
                LogManager.getLogger("sendEmailError").info("订单id:"+evalformId+" 店铺信息:"+ JSONObject.toJSONString(byId));
            }
        }
    }
}
